close all
addpath(genpath(pwd));
%profile on
%% Section 1 Setup files
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Step 1 Setup (running new Petrogen models)

% Name of file with run conditions... probably do not need to change unless
% it gets really messy:
infile='AAA_Step1_INFILE';

% Name of folder to save the results (I like to keep this the same):
Step1_subfolder_filename = 'Step1_Results';


%% Step 2 Setup (extracting Petrogen submodels)

% Name of folder to save the results:
Step2_subfolder_filename='Step2_ExtractedModels';
% Name of file with models to extract and plot:
Step2Step3_spreadsheet_name='BBB_Step2_ExtractGroups.xlsx';

% Enter as many Excel Sheets as you wish from the "Step2Step3_spreadsheet_name" spreadsheet to load:

ExtractedMelts_TabNames_all={'Figs5and6','Bulky','FigS2andS3','SingleMeltingModels','Fig5','Fig6'};
%ExtractedMelts_TabNames_all={'SingleIsobaric'};


%% Step 3 and 4 Setup (plotting and extracting Petrogen submodels)
% Details needed to plot:

%Example 1 Isobaric batch melting of WKR
ExtractedMelts_TabName = 'SingleIsobaric';
DATANAME = 'WalterComparison';
whichPrimarySM2plot=[1:11];
whichFractionatedSM2plot = [1:11];
name4edits='';


% %Polybaric melting example 
% ExtractedMelts_TabName = 'Fig6';
% DATANAME = 'Fig6';
% whichPrimarySM2plot=[1:11];
% whichFractionatedSM2plot = [1:11];
% name4edits='';


% Probably don't need to change: 
% Name of folder to save plot:
Figures_subfolder='Figures';
Filename_Ds_FracCryst = 'Ds_FracCryst45'; % Can update in step [6]


% LEGEND MODIFICATIONS
SM_Markers = {'d'
    'd'
    'd'
    '>'
    '>'
    '>'
    's'
    's'
    's'
    'o'
    'o'};

SM_LineWidth = [0.5 .75 1.5 0.5 .75 1.5 0.5 .75 1.5 1 1]';
SM_MarkerSize = [10 6 10 10 6 10 10 6 10 16 12]' ;

markersizegalehere=15;
LineWidthgalehere=3;


%%
SMlabels = {'First Extracted Garnet'; 'Average Extracted Garnet'; 'Last Extracted Garnet'
    'First Extracted Spinel'; 'Average Extracted Spinel'; 'Last Extracted Spinel'
    'First Extracted Plagioclase'; 'Average Extracted Plagioclase'; 'Last Extracted Plagioclase'
    'Full Pool'; 'On-Axis (Narrow) Pool'};

SMTable = table(SMlabels,SM_Markers,SM_MarkerSize,SM_LineWidth);

%% Section 2 Prompted inputs below
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
promptreponseMASTER = input(sprintf(...
    'Do you want to: \n [1] Run new Petrogen models \n [2] Extract submodels for plotting and saving \n [3] Plot (3a) or replot (3b) submodel results \n [4] Save results to a spreadsheet \n [5] Remake paper figures \n [6] Import new trace element fractional crystallization Ds? \n 1, 2, 3, 4, 5, or 6 [1]:'),'s');


%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% RUN PETROGEN

if strcmp(promptreponseMASTER,'1') ==1
    close all
    clearvars -except infile worksheetName2Save Step1_subfolder_filename Step2Step3_spreadsheet_name
    
    disp(sprintf('\n Okay, will run new melting models with the following melting conditions:'))
    
    eval(infile)
    
    if strcmp(IsobaricOrPolybaric,'Isobaric')
        worksheetName2Save
        IsobaricOrPolybaric
        forceSpPlag
        Porosity_vary
        PIsobaric_vary
        BulkCompositions_vary
        dFdPwaterchange_vary
        initialwatercontent_vary
        MaxF
    else if strcmp(IsobaricOrPolybaric,'Polybaric')
            worksheetName2Save
            IsobaricOrPolybaric
            GeodynamicModel
            BulkCompositions_vary
            TP_vary
            afewfunrnuns_U_vary
            Porosity_vary
            initialwatercontent_vary
            dFdP_Type
            dFdP
            dFdPwaterchange_vary
            forceSpPlag
            AdiabatSlope
        end
    end

    
    
    checkinfile = input(sprintf('\n Are the above parameters correct?\n    Enter <strong>N</strong> to change, any key to continue:'),'s');
    
    
    if strcmp(checkinfile,'N')
        disp('okay, edit the infile right now, save it, and rerurn this program.')
        disp(sprintf('\n<strong>Opening the infile ''%s''...</strong>',infile))
        uiopen(infile,1)
        
        disp(sprintf('<strong>\nAlso opening the file where you can add new major and trace element sources ''%s''...</strong>',infile))
        disp('...Note: it is easier to update the trace element sources in the spreadsheet later in Step 2...')
   
        if ismac
            % Code to run on Mac platform
             macopen('AAA_PETROGEN_SourcesAndDs.xlsx');
        elseif isunix
            % Code to run on Linux platform
        elseif ispc
            % Code to run on Windows platform
           winopen('AAA_PETROGEN_SourcesAndDs.xlsx');
        else
            disp('Platform not supported')
        end
        

        disp('Exiting Now')
        return
    end


    [worksheetName2Save,Step1_subfolder_filename]=...
        XXX_Function_ExecuteSaveMultiple_PETROGEN2020(infile,worksheetName2Save,Step1_subfolder_filename);
    
    disp('      ')
    disp('      ')
    disp('      ')
    disp('*Find, edit, and redraw figures in code by searching for figure number e.g., figure(4) in the right file')
    disp('**In particular, you probably want to move the legends prior to saving!')
    disp('***When ready to save figures, execute command ''SaveFigures''')
    
    
    disp('Finished.')
    
    disp('      ')
    disp('      ')
    disp('      ')
    disp('<strong>Now go to the Step2Step3 spreadsheet and define models to extract and plot. \n When ready, rerun this program.</strong>')
    
    disp(sprintf('<strong>Attempting to open the default spreadsheet ''%s''...</strong>',Step2Step3_spreadsheet_name))
    if ismac
        % Code to run on Mac platform
          macopen(Step2Step3_spreadsheet_name)
    elseif isunix
        % Code to run on Linux platform
    elseif ispc
        % Code to run on Windows platform
           winopen(Step2Step3_spreadsheet_name)
    else
        disp('Platform not supported')
    end
    

    disp('      ')
    disp('<strong>Exiting now</strong>')
    
  
    return
  
end


%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% Export Models
if strcmp(promptreponseMASTER,'2') ==1
    close all
    clearvars -except Step2Step3_spreadsheet_name Step2_subfolder_filename ExtractedMelts_TabNames_all Audio
    
    fprintf('<strong>Okay! Make sure you have defined models and their symbol appearance in a spreadsheet. \n I can wait. </strong>')
    disp('      ')
    disp('      ')
    disp('      ')
    promptreponse = input(sprintf('Will use the Excel file  <strong>''%s''</strong> to extract models. \n To change enter ''N'' [N], otherwise press any key to continue:',Step2Step3_spreadsheet_name),'s');
    if strcmp(promptreponse,'N')
        Step2Step3_spreadsheet_name = input('Okay, what should it be?]:','s');
        fprintf('<strong>Okay! Will <strong>''%s''</strong> instead </strong>\n',Step2Step3_spreadsheet_name)
    else
        fprintf('<strong>Okay! Will use the default ''%s'' </strong>\n',Step2Step3_spreadsheet_name)
    end
    
    
    disp('      ')
    disp('      ')
    disp('      ')
    play(Audio);
    promptreponse = input(sprintf('<strong>Saving Step 2 results to the subfolder ''%s''</strong> \n To change enter ''N'' [N]:',Step2_subfolder_filename),'s');
    if strcmp(promptreponse,'N')
        Step2_subfolder_filename = input('Okay, what should it be?','s');
    end
    disp('      ')
    disp('      ')
    disp('      ')
    
    fprintf('<strong>Step2 filenames are automatically generated as Step2_``ExcelSheetname''.  \n Also plotting details for models (e.g., colors) are not being imported in Step2, that happens in Step3.</strong>\n')
    
    disp('      ')
    disp('      ')
    disp('      ')
    
    if iscell(ExtractedMelts_TabNames_all)==1
        
        
        disp('You have told me to extract models from the following tabs:')
        disp(ExtractedMelts_TabNames_all)
        numberStep2Tabs = size(ExtractedMelts_TabNames_all,2);
        
        promptreponse = input(sprintf('Are the above sheetnames (%d) for extraction correct? \n Enter ''N'' to change [N]:',numberStep2Tabs),'s');
        
        if strcmp(promptreponse,'N')
            ExtractedMelts_TabNames_all = input('Okay, what should they be?]:','s');
            fprintf('<strong>Okay! Will load the following instead: </strong>\n')
            disp(ExtractedMelts_TabNames_all)
        else
            fprintf('<strong>Okay! Will use those sheetnames listed above</strong>')
        end
        disp(sprintf('<strong>\nExtracting now...</strong>'))
        
           CHECKvariable=0;
        for lh = 1:size(ExtractedMelts_TabNames_all,2)
            ExtractedMelts_TabName = ExtractedMelts_TabNames_all{lh};
            WorksheetName2Save = sprintf('Step2_%s',ExtractedMelts_TabName);
            fprintf('\n')
            fprintf('\n')
            fprintf('Now extracting the following models in sheet ''%s'':\n \n',ExtractedMelts_TabName);
           % fprintf('.......')
           CHECKvariable=extractModels(Step2_subfolder_filename,Step2Step3_spreadsheet_name,ExtractedMelts_TabName,WorksheetName2Save);
           if CHECKvariable==1
               
               disp('Then go back to the spreadsheet and fix it')
               disp(sprintf('<strong>...Attempting to open the default spreadsheet where you can do this ''%s''...</strong>',Step2Step3_spreadsheet_name))
               if ismac
                   % Code to run on Mac platform
                   macopen(Step2Step3_spreadsheet_name)
               elseif isunix
                   % Code to run on Linux platform
               elseif ispc
                   % Code to run on Windows platform
                   winopen(Step2Step3_spreadsheet_name)
               else
                   disp('Platform not supported')
               end
               
               disp('Exiting now')
    
                return
            end
        end
        
    else
        
        promptreponse = input(sprintf('Is ``%s'' the right sheetname for extraction? \n Enter ''N'' to change [N]:',ExtractedMelts_TabNames_all),'s');
        if strcmp(promptreponse,'N')
            ExtractedMelts_TabNames_all = input('Okay, what should it be?]:','s');
            fprintf('<strong>Okay! Will load ``%s'' instead</strong>\n',ExtractedMelts_TabNames_all)
            disp(ExtractedMelts_TabNames_all)
        end
        fprintf('<strong>Extracting now...</strong>')
        ExtractedMelts_TabName = ExtractedMelts_TabNames_all;
        WorksheetName2Save = sprintf('Step2_%s',ExtractedMelts_TabName);
        extractModels(Step2_subfolder_filename,Step2Step3_spreadsheet_name,ExtractedMelts_TabName,WorksheetName2Save)
        
    end
    
    fprintf('\n')
    disp(sprintf('\nName of Folder that Step 2 Files are Saved in: <strong>''%s''</strong>\n',Step2_subfolder_filename))
    
    
    
    disp('<strong>Finished Extracting. Rerun this program to make plots or save data to a spreadsheet. Exiting now</strong>')
    return
    
end


%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% PLOT



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if strcmp(promptreponseMASTER,'3') ==1
    promptreponseMASTER = input(sprintf('\n Do you want to: \n [3a] Load extracted melts (new from this session or older) and go through setup \n [3b] Keep plotting and skip setup? \n <strong>NOTE: Only choose 3b if you have already done 3a once </strong> \n 3a/3b [3a]:'),'s');
end


if strcmp(promptreponseMASTER,'3b')==1
    fprintf('<strong>Okay! Will not clear any data, and will plot with the same symbols and other details </strong>\n')
end



if ismember(promptreponseMASTER,{'3a','4' '5'})==1
    fprintf('<strong>Okay! Let''s load data \n </strong>')
    
    clearvars -except SM_Markers SM_LineWidth SM_MarkerSize markersizegalehere LineWidthgalehere Step2Step3_spreadsheet_name ...
        SMTable SMlabels ...
        default1 default2 default3 WorksheetName2Save ExtractedMelts_TabName promptreponseMASTER...
        Step2FileName targetDataLabel figurePlottingScriptName whichPrimarySM2plot whichFractionatedSM2plot whichmodel Audio ...
        DATANAME name4edits NamesForFC Figures_subfolder Step2_subfolder_filename infile Filename_Ds_FracCryst
    
    
    addpath(genpath(pwd));
    % load imported data
    load('kimberlites')
    load('Galeetal2013_SuppTables')
    load(Filename_Ds_FracCryst) 
    
    
    load('Brown2020')
    load('Chauvel')
    load('HSDM')
    load('MK91')
    
    ColorsHERE
end


if strcmp(promptreponseMASTER,'5') ==1
    clear fignum
    fignum = input(sprintf('\nWhich figure? \n 5 and 6 [56] \n 7 and 8 [78] \n [9] \n [10] \n [11] \n [12] \n [13] \n [14] \n enter only #s:'),'s');
    fprintf('<strong>Okay, Will remake Fig ''%s'' as well as a few extras... </strong>\n',fignum)
    
    %Gather input parameters for plotting specific for the paper figures
    disp('.......')
    disp(sprintf('Reading script ''%s'' for figure plotting info','PaperFiguresSetup'))
    PaperFiguresSetup
end





if ismember(promptreponseMASTER,{'3a','4'})==1
    
    promptreponse = input(sprintf('\nWill use the Excel file <strong>''%s''</strong>. \n To change enter ''N'', otherwise press any key to continue: [N]',Step2Step3_spreadsheet_name),'s');
    if strcmp(promptreponse,'N')
        Step2Step3_spreadsheet_name = input('Okay, what should it be?]:','s');
        fprintf('<strong>Okay! Will <strong>''%s''</strong> instead </strong>\n',Step2Step3_spreadsheet_name)
    end
    
    
    disp(sprintf('\n<strong>!!!You can only plot/extract models listed in a single Excel sheet at the same time!!! \n (You can edit the code if you really want...)\n</strong>'))
    
    
    promptreponse = input(sprintf('\nWill use the Excel sheet/tab <strong>''%s''</strong> to load model info. \n To change enter ''N'', otherwise press any key to continue: [N]',ExtractedMelts_TabName),'s');
    if strcmp(promptreponse,'N')
        ExtractedMelts_TabName = input('Okay, what should it be?]:','s');
        fprintf('<strong>Okay! Will use <strong>''%s''</strong> instead </strong>\n',ExtractedMelts_TabName)
    end
    
    
    promptreponse = input(sprintf('\nWill use the DATANAME <strong>''%s''</strong> to tag models you wish to plot or extract. \n To change enter ''N'', otherwise press any key to continue: [N]',DATANAME),'s');
    if strcmp(promptreponse,'N')
        DATANAME = input('Okay, what should it be?]:','s');
        fprintf('<strong>Okay! Will use <strong>''%s''</strong> instead </strong>\n',DATANAME)
    end
    
    
    
    targetDataLabel = DATANAME;
    
end






if ismember(promptreponseMASTER,{'3a','4', '5'})==1
    
    %Read in which models to plot
    %Needs targetDataLabel, Step2Step3_spreadsheet_name, ExtractedMelts_TabName
    ReadinModelInfo
    if badmodelrun==1
        disp('Then go back to the spreadsheet and fix it')
        disp(sprintf('<strong>...Attempting to open the default spreadsheet where you can do this: ''%s''...</strong>',Step2Step3_spreadsheet_name))
        if ismac
            % Code to run on Mac platform
            macopen(Step2Step3_spreadsheet_name)
            
            disp(sprintf('<strong>Also opening the file where you can add new trace element sources: ''%s''...</strong>',infile))
            macopen('AAA_PETROGEN_SourcesAndDs.xlsx')
        elseif isunix
            % Code to run on Linux platform
        elseif ispc
            % Code to run on Windows platform
            winopen(Step2Step3_spreadsheet_name)
            disp(sprintf('<strong>Also opening the file where you can add new trace element sources: ''%s''...</strong>',infile))
            winopen('AAA_PETROGEN_SourcesAndDs.xlsx')
        else
            disp('Platform not supported')
        end
        
        disp('Exiting now')
        return
    end
    
    %Load Step 2 file
    disp('.......')
    %disp(sprintf('Loading Step2 file ''%s'' with extracted melting results','Step2FileName'))
    Step2FileName = sprintf('Step2_%s',ExtractedMelts_TabName);
    load(Step2FileName)
    
    
    %Recalculate trace elements and extract a bit of data
    CCC_SetUpFigures
    
end



if ismember(promptreponseMASTER,{'3a','5'})==1
    matches = strfind(desiredModels,'SM');
    tf = any(vertcat(matches{:}));
    if tf==1
        disp('      ')
        disp('      ')
        disp('      ')
        
        disp(sprintf('<strong>''Significant Melts'' will be plotted with the listed details:\n</strong>'))
        
        disp(SMTable)
        play(Audio);
        promptreponse = input(sprintf('<strong>To change enter ''N'', otherwise press any key to continue: [N]</strong>'),'s');
        if strcmp(promptreponse,'N')
            display('Okay, go manually change at top of this script and rerun. Exiting now')
            disp(sprintf('<strong>Opening the file ''%s''...</strong>',AAA_Master_MeltPlot_Petrogen))
            uiopen(AAA_Master_MeltPlot_Petrogen,1)   
            return
        end
        
        disp('      ')
        SMtoPlot = whichPrimarySM2plot';
        SMlabelstoPlot  = SMlabels(whichPrimarySM2plot);
        
        if size(SMtoPlot,1)==11
            disp('You have chosen to plot ALL ''Significant Melts''')
        else
            disp('You have chosen to plot SOME ''Significant Melts''')
            SMtable2 = table(SMtoPlot, SMlabelstoPlot);
            disp(SMtable2)
        end
        promptreponse = input(sprintf('<strong>To change enter ''N'', otherwise press any key to continue: [N]</strong>'),'s');
        if strcmp(promptreponse,'N')
            
            whichPrimarySM2plot = input(sprintf('\nOkay, which ones do you want to plot? Enter as a vector e.g., "[1 3 10 11]":\n'));
            display('Okay, changed the ''Significant Melts'' to plot to:')
            SMtoPlot = whichPrimarySM2plot';
            SMlabelstoPlot  = SMlabels(whichPrimarySM2plot);
            SMtable2 = table(SMtoPlot, SMlabelstoPlot);
            disp(SMtable2)
        end
    end
end



if ismember(promptreponseMASTER,{'3a','3b'})==1
    whichFigures2plot = input(sprintf('Which set of figures do you want to plot? \n[1] Geochemical, includes F,zeta (e.g, Figs 7,8,9,10) \n[2] Geochem-Geophysical (crustal thickness, spreading rate)(e.g.,Figs 5,6,11) \n[3] Major-trace-isotope (Figs 12-14) \n[4] F v Major elements\n:'));
    if whichFigures2plot==1
        figurePlottingScriptName = 'ddd_Step3_GenericFigures';
    else if whichFigures2plot==2
            figurePlottingScriptName = 'ddd_Step3_Generic_CrustalThicknessFigures';
        else if whichFigures2plot==3
                figurePlottingScriptName = 'ddd_Step3_Generic_MajorTraceIsotope';
                        else if whichFigures2plot==4
                figurePlottingScriptName = 'ddd_Step1_IsobaricFigures';
            end
        end
    end
end
end


if ismember(promptreponseMASTER,{'3a','3b','5'})==1
    %Make the figures
    disp('.......')
    disp(sprintf('Okay...Running script ''%s'' to plot figures...open this file to make edits',figurePlottingScriptName))
    
    
    eval(figurePlottingScriptName)
    
    
    %Execute any special edits to the axes, if any
    disp('.......')
    disp(sprintf('Running script ''%s'' to special edit axes',name4edits))
    eval(name4edits)
    
    disp('Finished Plotting')
    disp(sprintf('*Find, edit, and redraw figures searching for figure number e.g., figure(4) in the script ''%s''',figurePlottingScriptName))
    disp('**In particular, you probably want to move the legends prior to saving! (that does not require editing code...)')
   
    
    disp(sprintf('***Opening the m-file you can edit these figures:<strong>%s</strong>',figurePlottingScriptName))
    uiopen(figurePlottingScriptName,1)
    
     disp(sprintf('<strong>***When ready to save figures, execute command ''SaveFigures''</strong>'))
    
end



%%
if strcmp(promptreponseMASTER,'4') ==1
    
    promptreponse = input(sprintf('<strong>Saving Step 2 results to the subfolder ''%s''</strong> \n To change enter ''N'' [N]:',Step2_subfolder_filename),'s');
    if strcmp(promptreponse,'N')
        Step2_subfolder_filename = input('Okay, what should it be?','s');
    end
    disp('      ')
    disp('      ')
    disp('      ')
    
    
        worksheetName2Save2=sprintf('%s_DATANAME_%s',ExtractedMelts_TabName,DATANAME);
        filename = sprintf('Results_Petrogen_%s.xlsx',worksheetName2Save2);
        
    NormOrNot = input(sprintf('Do you want trace elements and trace element ratios output as \n [1] element abundances in ppm \n [2] normalized to %s? \n: ',normalizationLabel));
    
    while ismember(NormOrNot,[1 2])==0
        disp('Try again:')
         NormOrNot = input(sprintf('Do you want trace elements and trace element ratios output as \n [1] element abundances in ppm \n [2] normalized to %s? \n: ',normalizationLabel));
    end
    
    
    CatRatios = regexprep(RatioLabels,'/','');
    CatRatios = regexprep(CatRatios,'Eu/Eu*','EuAnomaly');
    
    if NormOrNot==1
        disp('Okay, saving trace elements as abundaces. Model trace element source info is saved in Sheet 1.')
        Labels = {ConstraintOptions{:} PetrogenMajorElement_Strings_Extracted{:} PetrogenTraceElement_Strings{:} CatRatios{:}};
        norminfo = sprintf('Trace elements and ratios reported as abudances (i.e., not normalized) to ''%s''',normalizationLabel);
    else if NormOrNot==2
            disp(sprintf('Okay, saving trace elements normalized to ''%s''. \n Model trace element source info is saved in Sheet 1.',normalizationLabel))
            tempTrace = strcat(PetrogenTraceElement_Strings,'_PUM');
            tempTraceRatios = strcat(CatRatios,'_PUM');
            Labels = {ConstraintOptions{:} PetrogenMajorElement_Strings_Extracted{:} tempTrace{:} tempTraceRatios{:}};
            norminfo = sprintf('Trace elements and ratios normalized to %s',normalizationLabel);
     
        end
    end
    
    
    
    Labels=regexprep(Labels,' ','');
    Labels{52}='Pbkbar';
    Labels{5}='cmyr';
    Labels{80}='H2Owt';
    Labels = matlab.lang.makeValidName(Labels);
    
    
    
    
    modelsInfoTable_forsaving = [modelsInfoTable; modelsInfoTable(1,:)];
    
    for kk=1:size(modelsInfoTable_forsaving,2)

        a=table2cell(modelsInfoTable_forsaving(end,kk));
        
        
        if iscellstr(a)==1
            modelsInfoTable_forsaving(end,kk)={''};
        else
            modelsInfoTable_forsaving(end,kk)={nan};
        end
    end
    modelsInfoTable_forsaving = [modelsInfoTable_forsaving; modelsInfoTable_forsaving(end,:)];
        
 
    modelsInfoTable_forsaving(end,1)= {norminfo};
 
 
    writetable(modelsInfoTable_forsaving,[pwd '/' Step2_subfolder_filename '/' filename],'Sheet','Sheet1','UseExcel',1)




    for jm=1:size(TabNames,2)
        clear data2export
        Subgroup = TabNames{jm};
        
        if NormOrNot==1
        Data2Copy = [eval(sprintf('%s_InfoALL',Subgroup)),...
            eval(sprintf('%s',Subgroup)),...
            eval(sprintf('%s_Trace',Subgroup)),...
            eval(sprintf('%s_DataRatios',Subgroup))];
        else
            Data2Copy = [eval(sprintf('%s_InfoALL',Subgroup)),...
            eval(sprintf('%s',Subgroup)),...
            eval(sprintf('%s_Trace',Subgroup))./TraceElements4Normalization,...
            eval(sprintf('%s_DataRatios',Subgroup))./TraceElements4Normalization_DataRatios];   
        end
        
        
        
        
        data2export = table(Data2Copy);
        data2export=splitvars(data2export,'Data2Copy','NewVariableNames',Labels);
        
       
        writetable(data2export,[pwd '/' Step2_subfolder_filename '/' filename],'Sheet',Subgroup,'UseExcel',1)
        
       
    end
     disp(sprintf('Finished exporting melt compositions to spreadsheet named: \n <strong>''%s''</strong> \n in folder: \n<strong>''%s''</strong>',filename,Step2_subfolder_filename));

end


%%
if strcmp(promptreponseMASTER,'6') ==1
    ZZZ_ImportFracCrystDs
end
%%


%profile viewer
